####################################################################
#***2019 analysis
## Packages
# To install and open the R packages that you need for this code. 
need <- c('tidyverse','readstata13','lfe','glue','rdrobust', 'stargazer','arm', 'broom', 'ggplot2', 'dotwhisker', 'gridExtra')
have <- need %in% rownames(installed.packages()) 
if(any(!have)) install.packages(need[!have]) 
invisible(lapply(need, library, character.only=T)) 

# Change path to whereever you place the models
# To set up the working directory. 
script_folder = dirname(rstudioapi::getSourceEditorContext()$path)
setwd(glue('{script_folder}'))
rm(list = ls())
setwd("../")

## load in RD data:
load("5prepdata/final_rd_data.RData")

rd.data<-rd.data[rd.data$won_election==1,] #keep only winners
#rd.data<-rd.data[!is.na(rd.data$mds1),] #keep only good values of mds1
rd.data.state<-rd.data %>%                                          #1
  group_by(state) %>%
  summarise(mean_ever_hle = mean(ever_hle), mean_mds1 = mean(mds1, na.rm=TRUE), mean_ratio = mean(cong_leg_ratio)) 
rd.data.state<-rd.data.state[!is.na(rd.data.state$mean_mds1),]
rd.data.state$mean_mds1<-(rd.data.state$mean_mds1-mean(rd.data.state$mean_mds1, na.rm=TRUE))/sd(rd.data.state$mean_mds1, na.rm=TRUE)
sd(rd.data.state$mean_mds1, na.rm=TRUE)
lm(mean_ever_hle~mean_mds1 , data=rd.data.state)


# THIS PRODUCES FIGURE 7
rd.data.state %>% 
  rename(state.name = state) %>% 
  left_join(data.frame(state.name, state.abb)) %>% 
  ggplot(aes(x=mean_mds1, y=mean_ever_hle, label=state.abb)) + 
  geom_text() + geom_smooth(method="lm") +
  labs(y="Share of candidates ever contesting national office", x="Professionalism score") + #, caption="Correlation between state legialtive professionalism and upward candidacy"
  theme_bw() 

  ggsave(file = "7tex/manuscript/tables/sourcefiles/Figure 7.pdf", units="in", width=6, height=4)



